import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import type { AsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import type { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";
import type { ActionReducerMapBuilder } from "@reduxjs/toolkit";
import type { Good, SearchParams } from "@/type/SearchType";
import { searchGoodListAPI } from "@/api/searchAPI";

type PushSearchListAction = {
   type: string
   payload: string
}

type InitialState = {
   searchList: string[],
   goodList: Good[]
}

const initialState: InitialState = {
   searchList: JSON.parse(localStorage.getItem("list") as string) || [],
   goodList: [],
};

/**
 * @description 获取商品列表的asyncThunk函数
 * */
export const searchGoodListThunk: AsyncThunk<Good[], SearchParams, AsyncThunkConfig> = createAsyncThunk("searchGoodList", async (params: SearchParams, { rejectWithValue }) => {
   try {
      const { data: { list } } = await searchGoodListAPI(params);
      return list.data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const searchStore = createSlice({
   name: "searchStore",
   initialState,
   reducers: {
      /**
       * @description 往searchList数组前面添加一个元素的同步函数
       * */
      pushSearchList(state: InitialState, action: PushSearchListAction) {
         const goodsName: string = action.payload;
         const index = state.searchList.findIndex(item => item === goodsName);
         if (index === -1) {
            state.searchList.unshift(goodsName);
         } else {
            state.searchList.splice(index, 1);
            state.searchList.unshift(goodsName);
         }
      },

      /**
       * @description 清空searchList数组
       * */
      clearSearchList(state: InitialState) {
         state.searchList = [];
      },

   },
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(searchGoodListThunk.fulfilled, (state: InitialState, action: PayloadAction<Good[]>) => {
         state.goodList = action.payload;
      });
   },
});


export const { pushSearchList, clearSearchList } = searchStore.actions;

export default searchStore.reducer;
